<?php

namespace app\common\service;


use app\common\model\Ip;
use think\facade\Request;

class ServerOptionHistory extends Base

{
    function list($params, $limit)
    {
        $db = db('server_option_history');

        //条件筛选
        if(isset($params['type']) && !empty($params['type'])){
            $db->where('soh.type',$params['type']);
        }
        if(isset($params['content']) && !empty($params['content'])){
            $db->where('soh.content','like','%'.$params['content'].'%');
        }
        if(isset($params['ctime']) && !empty($params['ctime'])){

            $time_stamp_start = strtotime($params['ctime']);
            $time_stamp_end = $time_stamp_start + 86400;

            $db->where('soh.ctime','between',[$time_stamp_start, $time_stamp_end]);
        }
        if(isset($params['user_name']) && !empty($params['user_name'])){
            $db->where('su.show_name','like','%'.$params['user_name'].'%');
        }
        if(isset($params['ip']) && !empty($params['ip'])){
            $db->where('soh.ip','like','%'.$params['ip'].'%');
        }


        $field = 'soh.id, soh.type, soh.content, soh.ctime, soh.address,
         soh.ip, su.show_name as user_name';
        //查询查询数据
        $data = $db->alias('soh')
            ->join('server_user su','soh.user_id = su.id')
            ->order('soh.ctime desc')
            ->field($field)
            ->paginate($limit)->toArray();

        return $data;
    }

    /**
     * @name 添加用户操作日志
     * @author wx
     * @date 2020/5/28 13:27
     */
    function addUserLog()
    {
        global $logContent;
        global $errCode;
        global $errMsg;

        if(empty($logContent)){
            return true;
        }

        $status = 1;
        if($errCode != 200){
            $status = 0;
            $logContent = $logContent . ' [ 失败原因：'.$errMsg.']';
        }

        //验证用户
        $userInfo = Request::param('user_info');




        if(empty($userInfo)){
            return true;
        }

        //1. 查询ip对应的地址address
        $addressR = $_SERVER['DOCUMENT_ROOT'].'/static/IP/qqzeng.dat';
        if(!file_exists($addressR))
        {
            return true;
        }
        $ipServer = new Ip($addressR);
        $ipInfo = $ipServer->getlocation($_SERVER['REMOTE_ADDR']);
        $address = $ipInfo['country'].$ipInfo['province'].$ipInfo['city'].$ipInfo['area'];

        //构造数据
        $addLogData['user_id'] = $userInfo['id'];
        $addLogData['type'] = 1;
        $addLogData['content'] = $logContent;
        $addLogData['address'] = $address;
        $addLogData['ip'] = $_SERVER['REMOTE_ADDR'];
        $addLogData['status'] = $status;
        $addLogData['ctime'] = time();

        //添加数据
        db('server_option_history')->insert($addLogData);
    }
}